package com.hgyc.mom.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hgyc.mom.common.enums.CommonStatus;
import com.hgyc.mom.system.entity.SysOrg;
import com.hgyc.mom.system.vo.OrgVO;
import com.hgyc.mom.system.mapper.SysOrgMapper;
import com.hgyc.mom.system.service.SysOrgService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 组织结构 服务实现类
 * </p>
 *
 * @author fwj
 * @since 2025-02-20
 */
@Service
public class SysOrgServiceImpl extends ServiceImpl<SysOrgMapper, SysOrg> implements SysOrgService {

    @Override
    public List<OrgVO> all() {
        LambdaQueryWrapper<SysOrg> wrapper = new LambdaQueryWrapper<SysOrg>()
                .eq(SysOrg::getStatus, CommonStatus.ENABLE.getValue());
        List<SysOrg> allMenu = list(wrapper);

        return this.convertToTree(allMenu);
    }

    private List<OrgVO> convertToTree(List<SysOrg> orgs) {
        Map<Long, List<OrgVO>> parentChildrenMap = new HashMap<>();
        for (SysOrg org : orgs) {
            Long parentId = org.getParentId();

            OrgVO orgVO = new OrgVO();
            BeanUtils.copyProperties(org, orgVO);
            // 将当前菜单项添加到父菜单项的子菜单项列表中
            List<OrgVO> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
            children.add(orgVO);
            parentChildrenMap.put(parentId, children);

        }
        // 将根节点的子菜单项列表转换为树形结构
        List<OrgVO> rootChildren = parentChildrenMap.getOrDefault(0L, new ArrayList<>());
        for (OrgVO children : rootChildren) {
            convertToTree(children, parentChildrenMap);
        }
        return rootChildren;
    }

    private void convertToTree(OrgVO parent, Map<Long, List<OrgVO>> parentChildrenMap) {
        Long parentId = parent.getId();
        List<OrgVO> children = parentChildrenMap.getOrDefault(parentId, new ArrayList<>());
        parent.setChildren(children);
        for (OrgVO child : children) {
            convertToTree(child, parentChildrenMap);
        }
    }
}
